package com.example.demo.framework;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

@ControllerAdvice
public class GlobalExceptionHandler implements HandlerExceptionResolver {

	Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse res, Object obj,
			Exception ex) {
		responseCrossOrigin(res);
		String code = ErrorCode.ERROR_10999.getCode();
		String msg = ErrorCode.ERROR_10999.getMsg();
		JSONObject json = new JSONObject();
		if (ex instanceof BusinessException) {
			code = ex.getMessage().split(";")[0];
			msg = ex.getMessage().split(";")[1];
		} else if (ex instanceof ConstraintViolationException) {
			ConstraintViolationException e = (ConstraintViolationException) ex;
			StringBuilder errorMsg = new StringBuilder();
			for (ConstraintViolation<?> cv : e.getConstraintViolations()) {
				errorMsg.append(cv.getPropertyPath() + cv.getMessage()).append(";");
			}
			code = ErrorCode.ERROR_10002.getCode();
			msg = errorMsg.toString();
		}
		json.put("code", code);
		json.put("msg", msg);
		try {
			res.getWriter().write(json.toString());
			res.getWriter().flush();
			res.getWriter().close();
		} catch (IOException e) {
			log.error("与客户端通讯异常:" + e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 支持跨域
	 * 
	 * @param response
	 */
	private void responseCrossOrigin(HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
		response.setHeader("Access-Control-Allow-Headers",
				"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
	}

}
